"""
部门模型
作者：资深Flask讲师
功能：部门表定义
"""

from datetime import datetime
from myflask.tools.bd import db


class Department(db.Model):
    """
    部门表
    包含：部门基本信息
    """
    __tablename__ = 'departments'
    
    # 基本字段
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='部门ID')
    name = db.Column(db.String(100), unique=True, nullable=False, comment='部门名称')
    description = db.Column(db.String(255), nullable=True, comment='部门描述')
    
    # 部门经理ID（可选）
    manager_id = db.Column(db.Integer, nullable=True, comment='部门经理用户ID')
    
    # 状态字段
    status = db.Column(db.Integer, default=1, comment='状态：1-正常，0-禁用')
    
    # 时间字段
    created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    def to_dict(self, include_users=False):
        """转换为字典（用于API返回）"""
        data = {
            'id': self.id,
            'name': self.name,
            'description': self.description,
            'manager_id': self.manager_id,
            'status': self.status,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
        }
        
        # 包含部门员工列表
        if include_users:
            data['users'] = [user.to_dict(include_department=False) for user in self.users]
            data['user_count'] = len(self.users)
        
        return data
    
    def __repr__(self):
        return f'<Department {self.name}>'

